import { ScrollView, View } from "@tarojs/components";
import PetMoment from "../../components/petMoment/index";    
import './index.scss';
import { useLoad } from "@tarojs/taro";
import { useUserInfo } from "@/hooks/useUserInfo";
import apiRequest from "@/service/apiRequest";
import { useState } from "react";
import { IMG_URL } from "@/constants/api";
import { AtIcon } from "taro-ui";

import "taro-ui/dist/style/components/icon.scss";
import EmptyComponent from "../../components/empty/index";
import PetMomentList from "@/petMoments/components/petMomentList";

const PER_PAGE = 10;

function PetMoments() {
    const { userInfo } = useUserInfo();
    const [page, setPage] = useState<number>(1);
    const [totalCount, setTotalCount] = useState<number>(0);
    const [petMomentList, setPetMomentList] = useState<PetMomentItem[]>([]);
    
    const requestPostsList = async () => {
        if (!userInfo.userId) {
            return
        }
        let res = await apiRequest.get("/api/posts", {
            userId: userInfo.userId,
            page,
            perPage: PER_PAGE,
        }, {isShowLoading: false});
        if (res && res.posts) {
            setPetMomentList([...petMomentList, ...res.posts]);
            setTotalCount(res.total);
            setPage(page + 1);
        }
    }

    const refreshList = (id) => {
        let list = petMomentList.filter((item) => {
            return item.id !== id;
        })
        setPetMomentList(list);
        let totalCountComputed = totalCount >= 1 ? totalCount - 1 : 0;
        setTotalCount(totalCountComputed);
    }

    useLoad(() => {
        requestPostsList();
    })

    const handleScrollToLower = async () => {
        console.log("到底了");
        if (petMomentList.length >= totalCount) {
            return
        }
        requestPostsList();
    }

    if (petMomentList.length === 0 && totalCount === 0) {
        return (
            <EmptyComponent />
        )
    }

    return (
        <ScrollView
            className='page-moment'
            scrollY
            scrollWithAnimation
            enablePassive
            onScrollToLower={handleScrollToLower}
        >
            <PetMomentList list={petMomentList} refreshList={refreshList} />
            {/* 底部加载中 */}
            {
                petMomentList.length >= totalCount ? (
                    <View className="flex-c-c it-s-over-now">已经到底了～</View>
                ) : (
                    <View className="loading-box flex-c-c-c">
                        <AtIcon value='loading-3' size='30' color='#666666' className="loading-icon"></AtIcon>
                        <View className="loading-t">加载中</View>
                    </View>
                )
            }
        </ScrollView>
    )
}
export default PetMoments;